﻿using Consul;

namespace ConsulDemo.Consul
{
    public static class ConsulExtensions
    {

        public static void RegisterConsul(this IConfiguration configuration, string enviroment, string configName = "ConsulConfig")
        {

            var config = configuration.GetSection(configName).Get<ConsulConfig>();

            ConsulClient consulClient = new(delegate (ConsulClientConfiguration x)
            {
                x.Address = new Uri(config.Address);
                x.Datacenter = config.Datacenter;
            });

            var httpCheck = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔，或者称为心跳间隔
                HTTP = $"http://{config.IP}:{config.Port}/Health",//健康检查地址
                Timeout = TimeSpan.FromSeconds(5)
            };


            // Register service with consul
            var registration = new AgentServiceRegistration()
            {
                Checks = new[] { httpCheck },
                ID = $"{config.ServiceName}-{config.IP}:{config.Port}",
                Name = config.ServiceName,
                Address = config.IP,
                Port = config.Port,
                Tags = new[] { $"urlprefix-/{config.ServiceName}{config.Weight}", enviroment }//添加 urlprefix-/servicename 格式的 tag 标签，以便 Fabio 识别
            };
            consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册，内部实现其实就是使用 Consul API 进行注册（HttpClient发起）
        }


    }
}
